use strict;
use CGI;
use Digest::SHA1 qw(sha1_base64);
package cookie;
my $cookie_db="test.db";

sub set {
	my $uid = shift;
	my $ip = shift;

	if(my $already = logged_in($uid)) {
		return $already;
	}
	my $hash = Digest::SHA1::sha1_base64(rand());

	my $id_string = $hash."|".$uid;

	add_tuple($hash, $uid, $ip);
	return $id_string;
}

sub add_tuple {
	my $hash = shift;
	my $uid = shift;
	my $ip = shift;
	my $DB_string = join("|", $hash, $uid, $ip);
		
	open FD, ">>".$cookie_db or die $!;
	print FD $DB_string."\n";
	close FD;
}

sub remove_tuple {
	my $uid = shift;
	open FD, "<".$cookie_db or die $!;
	my @whole_db = <FD>;
	close FD;
	open FD, ">".$cookie_db or die $!;
	foreach my $l (@whole_db) {
		if((split(/\|/, $l))[1] ne $uid) {
			print FD $l;
		}
	}
	close FD;
}

sub check_tuple {
	my $hash = shift;
	my $uid = shift;
	my $ip = shift;
	open FD, "<".$cookie_db or die $!;
	my $db_hash;
	my $db_uid;
	my $db_ip;
	while (my $line = <FD>) {
		($db_hash, $db_uid, $db_ip) = split(/\|/, $line);
		chomp $db_ip;
		if(($db_hash eq $hash) 
			&& ($db_uid eq $uid) 
			&& ($db_ip eq $ip)) {
			return $db_uid;
		}
	}
	close FD;
	return 0;
}

sub logged_in {
	my $uid = shift;
	open FD, "<".$cookie_db or die $!;
	my $db_hash;
	my $db_uid;
	my $db_ip;
	while (my $line = <FD>) {
		($db_hash, $db_uid, $db_ip) = split(/\|/, $line);
		if(($db_uid eq $uid)) {
			chomp $db_ip;
			return $line;
		}
	}
	close FD;
	return 0;
}
1;

